package com.chengh.nami.common.request;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chengh.nami.common.constants.SqlConstants;
import com.chengh.nami.common.utils.SqlUtils;
import com.chengh.nami.common.utils.StringUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;

/**
 * @author
 * 分页查询类
 */
@Getter
@Setter
@Slf4j
public class PageQuery implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 分页大小
     */
    private Long pageSize;

    /**
     * 当前页数
     */
    private Long pageNum;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private String isAsc;

    /**
     * 默认开始页
     */
    public static final long DEFAULT_PAGE_NUM = 1L;

    /**
     * 默认每页大小为10
     */
    public static final long DEFAULT_PAGE_SIZE = 10L;


    /**
     * 组装成mybatisPlus分页插件需要的Page类
     */
    public <T> Page<T> build() {
        long pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
        long pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        log.info("分页获得数据: {}, {}", pageNum, pageSize);
        Page<T> page = new Page<>(pageNum, pageSize);
        OrderItem orderItem = buildOrderItem();
        if(!ObjectUtils.isEmpty(orderItem)) {
            page.addOrder(orderItem);
        }
        return page;
    }


    private OrderItem buildOrderItem() {
        if (StringUtils.isNotEmpty(orderByColumn)) {
            // 检查sql是否合规
            String orderBy = SqlUtils.escapeOrderBySql(orderByColumn);
            // 驼峰转下划线
            orderBy = StrUtil.toUnderlineCase(orderBy);
            if (SqlConstants.ASC.equals(isAsc)) {
                return OrderItem.asc(orderBy);
            } else if (SqlConstants.DESC.equals(isAsc)) {
                return OrderItem.desc(orderBy);
            }
        }
        return null;
    }

}
